<template>
    <div>
        <el-page-header :icon="ArrowLeft">

            <template #title>
                <span @click="back">返回</span>
            </template>

            <template #content>
                <span class="fs-14"> 诊所管理 </span>
                <el-icon style="vertical-align: -3px;">
                    <Right />
                </el-icon>
                <span class="fs-14"> 诊所信息 </span>
            </template>
        </el-page-header>


        <!-- 新增表单 -->
        <el-form ref="ruleFormRef" :model="form" label-width="120px" class="mt-12" :rules="rules">
            <el-form-item label="诊所名称" prop="name">
                <el-input v-model="form.name" class="input-width" />
            </el-form-item>
            <el-form-item label="诊所地址" prop="address">
                <el-input v-model="form.address" class="input-width" />
            </el-form-item>
            <el-form-item label="星级" prop="star">
                <el-select v-model="form.star" value-key="value" placeholder="请选择星级" class="input-width">
                    <el-option v-for="item in stars" :key="item.value" :label="item.lable" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" class="input-width" />
            </el-form-item>
            <el-form-item label="营业时间" prop="date">
                <div class="input-width">
                    <el-date-picker format="YYYY-MM-DD" v-model="form.date" type="daterange" range-separator="至"
                        start-placeholder="起始时间" end-placeholder="结束时间" />
                </div>
            </el-form-item>
            <el-form-item label="诊所特点" prop="desc">
                <el-input v-model="form.desc" type="textarea" />
                <p>还剩 <span>{{ descRemain }}</span> 字</p>
            </el-form-item>


            <!-- 上传图片 -->
            <el-form-item label="添加照片">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:4523/m1/2578626-0-default/upload"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'
import { ArrowLeft, Right, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { useNavigate } from '../hooks'
import { useRoute } from 'vue-router'
import { clinicadd, clinicinfo, clinicedit } from '../api'

// do not use same name with ref
const form = reactive({
    name: '',
    address: '',
    star: "",
    phone: '',
    date: [],
    desc: '',
    imgs: []
})

const route = useRoute()
const id = ref(route.query.id)
// console.log(id.value)
const stars = ref([{ value: 1, lable: "一星" }, { value: 2, lable: "二星" }, { value: 3, lable: "三星" }, { value: 4, lable: "四星" }, { value: 5, lable: "五星" }])

// 图片上传
const imageUrl = ref('')

const navigator = useNavigate()
const navigateTo = (url: string) => {
    navigator.navigateTo(url)
}
const back = function () {
    console.log('back,....')
    navigator.back()
}



const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {

    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    form.imgs = response.data
}


const picWhiteList = ["image/jpeg", "image/png"]

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // if (rawFile.type !== 'image/jpeg') {
    if (picWhiteList.indexOf(rawFile.type) === -1) {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}


// 计算诊所特点还剩多少个字
const descRemain = computed(() => {
    return 800 - form.desc.length
})


// 验证规则
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入诊所名称', trigger: 'blur' },
        { min: 3, max: 10, message: '诊所名称在3到10位之间', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '请输入诊所地址', trigger: 'blur' }
    ],
    star: [
        { required: true, message: '请选择诊所星级', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入诊所联系方式', trigger: 'blur' },
        { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' },
    ],
    date: [
        { required: true, message: '请选择诊所营业时间', trigger: 'blur' },
    ],
    desc: [
        { required: true, message: '请输入诊所特点', trigger: 'blur' },
        { min: 1, max: 800, message: '诊所特点文本长度需要小于800字', trigger: 'blur' },
    ]
})

const ruleFormRef = ref<FormInstance>()

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

onMounted(async () => {

    resetForm(ruleFormRef.value)

    if (id.value) {
        const res = await clinicinfo({ id: id.value })

        for (let key in res[0]) {
            form[key] = res[0][key]
        }

        imageUrl.value = form.imgs[0]
    }

})

const submitForm = async (formEl: FormInstance | undefined) => {
    console.log("提交表单", formEl)
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {

            form.date = form.date.map(d => {
                console.log(d)
                console.log(d.getTime())
                return d.getTime()
            })
            if (id.value) {
                form.id = id.value
                const res = await clinicedit(form)
            } else {
                const res = await clinicadd(form)
            }

            navigateTo("/clinic/list")

        } else {
            console.log('error submit!', fields)
        }
    })
}


</script>

<style scoped lang="scss">
.input-width {
    width: 360px;
}

.avatar-uploader .avatar {
    width: 90px;
    height: 90px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    text-align: center;
}
</style>